<template>
  <div class="MaterialsReplaceDialog-box">
    <t-dialog
      placement="center"
      v-model:visible="store.unitEditShow"
      header="编辑单元信息"
      :confirm-on-enter="false"
      :on-cancel="onCancel"
      :on-esc-keydown="onEscKeydown"
      :on-close-btn-click="onCloseBtnClick"
      :on-overlay-click="onOverlayClick"
      :on-close="close"
      :on-confirm="onConfirmAnother"
    >
      <div class="form-box">
        <div class="form-box-top">
          <t-form ref="form" :rules="FORM_RULES" :data="formData" :colon="true" @submit="onSubmit">
            <t-row>
              <t-col :span="12">
                <div class="from-title-box">
                  <div>
                    <span class="from-title-box-tip">*</span>
                    <span class="from-title-box-name">单元标题</span>
                  </div>
                </div>

                <t-form-item label="" name="name">
                  <div class="item-flex">
                    <t-input
                      style="width: 400px"
                      show-limit-number
                      :maxlength="16"
                      v-model="formData.text"
                      placeholder="请输入单元标题"
                    ></t-input>
                    <div class="ai-icon-box" @click="setdrawervisible">
                      <div class="ai-icon-box-shadow"></div>
                      <img :src="publicUrls + `door/aiIcon.png`" alt="" />
                    </div>
                  </div>
                </t-form-item>
              </t-col>
              <t-col :span="7" style="">
                <div class="from-title-box">
                  <span class="from-title-box-name">单元副标题</span>
                </div>
                <t-form-item label="" name="subTitle">
                  <div class="item-flex">
                    <t-input
                      style="width: 580px"
                      show-limit-number
                      :maxlength="30"
                      v-model="formData.subTitle"
                      placeholder="套用模版后，副标题会以“——”符号与主标题连接"
                    ></t-input>
                    <div class="ai-icon-box" @click="setdrawervisible">
                      <div class="ai-icon-box-shadow"></div>
                      <img :src="publicUrls + `door/aiIcon.png`" alt="" />
                    </div>
                  </div>
                </t-form-item>
              </t-col>
              <t-col :span="12" style="">
                <div class="text-wper">
                  <div class="from-title-box from-title-box-sb">
                    <span class="from-title-box-name">单元描述</span>
                    <div class="ai-icon-box" @click="setdrawervisible">
                      <div class="ai-icon-box-shadow"></div>
                      <img :src="publicUrls + `door/aiIcon.png`" alt="" />
                    </div>
                  </div>
                </div>
              </t-col>

              <t-col :span="12" style="margin-bottom: 0px">
                <div class="description-box" style="margin-bottom: 0px">
                  <t-textarea
                    style="width: 100%"
                    :autosize="{ minRows: 5, maxRows: 8 }"
                    v-model="formData.description"
                    placeholder="请输入单元描述,最大字数5000字"
                    :maxlength="5000"
                  ></t-textarea>
                </div>
              </t-col>
              <t-col :span="12">
                <div class="right-box" v-if="store.isUploadRadio">
                  <t-loading size="small" :loading="audioLoading && !audioVisible" show-overlay>
                    <div class="style-audio-add" @click="creatAi">
                      <i class="doorIcon"> &#xe652; </i>
                      <span> 生成语音 </span>
                    </div>
                  </t-loading>
                </div>
              </t-col>
              <t-col :span="12" style="margin-bottom: 20px">
                <div class="from-title-box">
                  <div>
                    <span class="from-title-box-name">全景链接</span>
                    <span class="from-title-box-tip"></span>
                  </div>
                </div>

                <t-form-item label="">
                  <t-input :maxlength="100" v-model="formData.digitalShowroom" placeholder="请输入全景链接"></t-input>
                </t-form-item>
              </t-col>
              <t-col :span="12">
                <t-form-item label="语音讲解" v-if="store.isUploadRadio">
                  <div class="hw-from-content">
                    <div class="from-title-box">
                      <span class="from-title-box-name">语音讲解</span>
                    </div>
                    <t-loading size="small" :loading="audioLoading && !audioVisible" show-overlay text="语音生成中...">
                      <div class="audio-list-box-upload-parent" @click="openaudioVisible" v-if="!formData.audio.url">
                        <div class="audio-list-box-upload">
                          <i class="doorIcon"> &#xe652; </i>
                          <span> 添加音频 </span>
                        </div>
                      </div>

                      <HWplayer
                        :editType="true"
                        :audio="formData.audio"
                        v-else
                        @editAudioUrl="openaudioVisible"
                        @delAudioUrl="delAudioUrl"
                      />
                    </t-loading>
                    <span class="audio-tip">支持10M以内MP3格式音频，最多1条</span>
                  </div>
                </t-form-item>
              </t-col>
              <t-col :span="12">
                <div class="from-title-box">
                  <span class="from-title-box-name">单元图片</span>
                </div>
                <div class="upload-parent">
                  <div class="img-boxs" v-if="formData.coverUrl">
                    <div class="img-boxs-icon">
                      <t-tooltip content="查看图片">
                        <div class="img-boxs-icon-item" @click="lookcoverUrl()">
                          <i class="doorIcon">&#xe630;</i>
                        </div>
                      </t-tooltip>
                      <t-tooltip content="删除图片">
                        <div class="img-boxs-icon-item" @click="delimg(index)">
                          <i class="doorIcon">&#xe634;</i>
                        </div>
                      </t-tooltip>
                    </div>
                    <img
                      class="upload-boxs-item t-image t-image--fit-contain t-image--position-center"
                      :src="urls + formData.coverUrl + webUrls"
                      alt=""
                    />
                  </div>
                  <t-upload
                    v-else
                    ref="uploadRef1"
                    v-model="filelist1"
                    :max="1"
                    accept=".png,.jpg"
                    :onSelectChange="beforeUpload"
                    :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                    @fail="handleFail"
                  >
                    <div class="upload-boxs">
                      <i class="doorIcon">&#xe657;</i>
                      <span>点击上传图片</span>
                    </div>
                  </t-upload>
                </div>
                <span class="tips">支持2M以内JPG、PNG图片。</span>
              </t-col>
            </t-row>
          </t-form>
        </div>
        <div class="form-box-bottom">
          <t-button @click="close" theme="default" variant="outline">取消</t-button>
          <t-button @click="onConfirmAnother">确定</t-button>
        </div>
      </div>
    </t-dialog>
    <div class="ai-drawer">
      <t-drawer v-model:visible="drawervisible">
        <AIcomponent v-if="drawervisible" />
      </t-drawer>
    </div>
  </div>
  <audioUploads
    ref="audioUploadRef"
    v-if="audioVisible"
    :maxLengh="5000"
    :unitInfo="formData"
    :info="formData.audio"
    :visible="audioVisible"
    @sbumitAudio="sbumitAudio"
    @emitTaskId="emitTaskId"
    @close="closeAudio"
  />
  <t-image-viewer v-model:visible="IMGvisible" :images="[urls + formData.coverUrl + webUrls]"> </t-image-viewer>
  <setAcatar @submit="clieSubmit" :visible="clievisible" @close="clieclose" :imgCode="imgCode" @setImg="cliesetImg" />
</template>  
   
<script setup lang="ts">
import audioUploads from '@/components/addExbition/addUnitAudioModel.vue';
import HWplayer from '@/components/audio/UnitAudio.vue';
import { createdTSAudio, queryTSAudio } from '@/api/exhibit/exhibit';
import { useCounter } from '@/hooks/audioHooks';
import { cloneDeep } from 'lodash';
import { moduleInfo } from '@/api/desgin/desgin';
import setAcatar from '@/components/avatar/Setavatar.vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { publicUrls, dataURLtoFile } from '@/utils/minxin';
import { url, heards, urls } from '@/utils/request/upload';
import { ref, reactive, computed, watch } from 'vue';
import { useProjectStore, useUserStore } from '@/store';
import { upLoadFn } from '@/utils/request/upload';
import { storeToRefs } from 'pinia';
const { audioTimer, audioLoading, clearaudioTimer } = useCounter();
const audioVisible = ref(false);
const audioUploadRef = ref(null);
const userStore = useUserStore();
const webUrls: string = '?imageView2/2/w/120/h/120/format/webp';
const store = useProjectStore();
const { unitEditShow } = storeToRefs(store);
const drawervisible = ref(false);
const filelist1 = ref([]);
const clievisible = ref(false);
const datas = reactive({
  file: {
    base64: '',
    contentType: '',
    fileName: '',
    format: '',
  },
});
const IMGvisible = ref(false);
const imgCode = ref<any>('');
const uploadAllFilesInOneRequest = ref(false);
const FORM_RULES = { text: [{ required: true, message: '标题必填' }] }; //表单校验
const formData = reactive({
  type: 1,
  number: 6,
  showpieceTotal: 8,
  subTitle: '',
  isAuxiliary: false,
  auxiliaryTotal: 4,
  digitalShowroom: '',
  children: [],
  id: 0,
  parentId: 0,
  text: '',
  value: '',
  coverUrl: '',
  description: '',
  sort: 10,
  level: 1,
  width: null,
  showpieceList: [],
  audio: {
    type: 3,
    url: '',
    description: '',
    name: '',
    taskId: '',
    taskStatus: -2,
  },
}); //表单

//语音模块函数
const openaudioVisible = () => {
  audioVisible.value = true;
};
const creatAi = () => {
  //通过按钮传入单元描述

  audioVisible.value = true;
  nextTick(() => {
    setTimeout(() => {
      audioUploadRef.value.setDescription(formData.description);
    }, 100);
  });
};
const sbumitAudio = (parmass: any) => {
  //语音传入
  let arrInfo = cloneDeep(parmass);
  // console.log(arrInfo);

  formData.audio = arrInfo;

  audioVisible.value = false;
};
const emitTaskId = (parmass: any) => {
  //语音传入TaskId
  let arrInfo = cloneDeep(parmass);
  formData.audio = arrInfo;
  if (formData.audio.taskId && formData.audio.taskStatus === 0) {
    audioLoading.value = true;
    // PollingTime();
  } else {
    audioLoading.value = false;
  }
};
const delAudioUrl = () => {
  //删除音频

  formData.audio.url = '';
  formData.audio.name = '';
};
const closeAudio = () => {
  audioVisible.value = false;

  if (formData.audio.taskId && formData.audio.taskStatus === 0) {
    audioLoading.value = true;
    PollingTime();
  }
};
const PollingTime = () => {
  //音频生成轮询函数 
  if (!formData.audio.taskId) { 
    clearaudioTimer(); 
    return;
  }
  clearaudioTimer();
  audioLoading.value = true;
  audioTimer.value = setInterval(() => {
    queryTSAudio(formData.audio.taskId).then((res) => {
      // console.log(res.data);
      if (res.data) {
        formData.audio.taskId = res.data.taskId;
        formData.audio.taskStatus = res.data.taskStatus;
        if (res.data.taskStatus === 1) {
          MessagePlugin.success('生成成功');
          clearaudioTimer();
          formData.audio.url = res.data.url;
          formData.audio.name = res.data.name;
        }
        if (res.data.taskStatus === -1) {
          clearaudioTimer();
        }
      }
    });
  }, 2500);
};
//其他模块

const onConfirmAnother = (context) => {
  if (!formData.text) {
    MessagePlugin.warning('请设置标题');
    return;
  }
  if (formData.text.length < 2) {
    MessagePlugin.warning('单元名称至少需要两个字');
    return;
  }
  formData.value = formData.coverUrl;
  store.sbmitItem(formData);

  // console.log('点击了确认按钮', context);

  store.unitEditShow = false;
};
const close = (context) => {
  //   console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
  clearaudioTimer();
  store.unitEditShow = false;
};
const setdrawervisible = () => {
  if (userStore.VipLevel === 0 && !store.isActivitys) {
    MessagePlugin.warning('当前会员等级不可使用，请升级会员等级');
    return;
  }
  drawervisible.value = true;
};
const onCancel = (context) => {};
const onEscKeydown = (context) => {};
const onCloseBtnClick = (context) => {};
const onOverlayClick = (context) => {};
const beforeUpload = (e: any) => {
  //回调钩子

  let file = e[0];
  console.log(file);
  if (
    file.type !== 'image/png' &&
    file.type !== 'image/jpg' &&
    file.type !== 'image/jpeg' &&
    file.type !== 'image/jpeg'
  ) {
    MessagePlugin.error('文件类型错误');
    return;
  }
  if (file.size / 1048576 > 2) {
    MessagePlugin.error('上传大小超出2M限制');
    return;
  }
  if (window.FileReader) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      let base64String = e.target.result;
      imgCode.value = base64String;

      datas.file = {
        raw: file,
        fileName: file.name,
        name: file.name,
        type: 'image',
      };

      clievisible.value = true;
    };
  }
  // upLoadFn(file, 5).then((res) => {
  //   // console.log(res);
  //   if (res) {
  //     formData.coverUrl = res;
  //     if (store.id !== 0) {
  //       // moduleSaveInfo(localStorage.getItem('projectId'), store.id, { coverUrl: res });
  //       // nextTick(() => {
  //       //   emit('setInfo', formData);
  //       //   emit('saveGroup');
  //       // });
  //     }
  //   } else {
  //     MessagePlugin.error('上传失败');
  //   }
  // });
};
const cliesetImg = (e: any) => {
  beforeUpload(e);
};
const clieSubmit = (e: String) => {
  let arrr = dataURLtoFile(e, datas.file.name);
  imgCode.value = e;
  datas.file.raw = arrr;
  clievisible.value = false;

  upLoadFn(datas.file, 5).then((res) => {
    // console.log(res);
    if (res) {
      formData.coverUrl = res;
    } else {
      MessagePlugin.error('上传失败');
    }
  });
};

const clieclose = (e: any) => {
  clievisible.value = false;
};
const lookcoverUrl = () => {
  IMGvisible.value = true;
};
const delimg = () => {
  formData.coverUrl = '';
};
const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

const handleFail = () => {};
const setUnitData = (id: number) => {
  moduleInfo(id).then((res) => {
    console.log(res.data);
    formData.audio = res.data.audio
      ? res.data.audio
      : {
          type: 3,
          url: '',
          description: '',
          name: '',
          taskId: '',
          taskStatus: -2,
        };
    if (formData.audio.taskId && formData.audio.taskStatus === 0) {
      audioLoading.value = true;
      PollingTime();
    } else {
      audioLoading.value = false;
    }
  });
};
watch(
  () => unitEditShow,
  () => {
    // console.log(store.itemList)

    let {
      type,
      number,
      showpieceTotal,
      subTitle,
      isAuxiliary,
      auxiliaryTotal,
      children,
      id,
      parentId,
      text,
      value,
      remarks,
      sort,
      level,
      width,
      showpieceList,
      digitalShowroom,
    } = store.itemList;
    // formData = store.itemList;
    console.log(store.itemList);
    if (store.unitEditShow) {
      setUnitData(id);
    }
    formData.digitalShowroom = digitalShowroom;
    formData.type = type;
    formData.number = number;
    formData.showpieceTotal = showpieceTotal;
    formData.subTitle = subTitle;
    formData.isAuxiliary = isAuxiliary;
    formData.auxiliaryTotal = auxiliaryTotal;
    formData.children = children;
    formData.id = id;
    formData.parentId = parentId;
    formData.text = text;
    formData.coverUrl = value;
    formData.description = remarks;
    formData.sort = sort;
    formData.level = level;
    formData.width = width;
    formData.showpieceList = showpieceList;
  },
  { deep: true },
);
</script>

<style scoped lang="less">
@import './index.less';
.from-title-box-sb {
  margin-bottom: 0px;
}
:deep(.t-textarea__inner) {
  padding-bottom: 24px;
}
:deep(.t-textarea__info_wrapper_align) {
  margin-top: 10px;
}
.audio-list-box-upload-parent {
  width: 124px;
  height: 36px;
}
.audio-list-box-upload {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  width: 124px;
  height: 36px;
  border-radius: 4px;
  border: 1px solid #e62b17;
  .doorIcon {
    color: #e62b17;
    font-size: 16px;
  }
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #e62b17;
    line-height: 24px;
    margin-left: 8px;
  }
}
.audio-tip {
  display: flex;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.38);
  line-height: 22px;
  margin-top: 8px;
}
.list-tip-box {
  display: flex;
  align-items: flex-end;
  width: 184px;
  // height: 184px;
  margin-left: 8px;
}
.list-tip-box-mg {
}
:deep(.t-radio) {
  margin-right: 0px;
}
//
:deep(.tox-tinymce) {
  height: 160px !important;
}
.right-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 12px;
}
.radio-parent {
  display: flex;
  align-items: center;
  // justify-content: center;
  height: 36px;
}
.style-audio-add {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  width: 108px;
  height: 36px;
  border-radius: 4px;
  border: 1px solid #e62b17;
  i {
    font-size: 18px;
    color: #e62b17;
  }
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #e62b17;
    line-height: 24px;
    margin-left: 4px;
  }
}
// .description-box
</style>